<template>
  <q-page class="page">
    <header class="q-pa-md fixed-top-left full-width bg-white " style="z-index: 20;">
      <div style="font-size: 18px; margin-top: 40px">已为您成功匹配以下机构</div>
      <div class="q-mt-xs" style="font-weight: bold; font-size: 16px">
        点击下方<span style="color: red; font-size: 18px"> 立即申请 </span>获取您的专属额度
      </div>
    </header>
    <div style="height: 130px"></div>

    <section class="q-pa-md">
      <div class="mechanism-card q-mt-md">
        <div class="q-pa-md">
          <div class="mark">
            <div class="mark-text">当前申请</div>
            <div class="flex justify-end q-mt-sm">
              <img src="~/assets/images/public/ok_select.png" style="width: 16px" />
            </div>
          </div>
          <div class="flex items-center">

            <div v-if="!orderItemTop" class="center q-mr-xs">
            </div>
            <div v-else-if="orderItemTop.companyLogo" class="center q-mr-xs">
              <img :src="orderItemTop.companyLogo" style="width: 25px; border-radius: 99999px" />
            </div>
            <div class="text-weight-bold">
              {{ orderItemTop?.companyName ?? '' }}
            </div>
          </div>
          <div class="text-weight-bold" style="font-size: 16px; margin-top: 10px">
            {{ orderItemTop?.companyTitle ?? '' }}
          </div>
          <div style="color: #999; font-size: 13px" class="q-mt-xs">
            {{ orderItemTop?.companySubTitle ?? '' }}
          </div>
        </div>
      </div>

      <div class="select-card q-pa-md q-mt-md" v-if="!!orderItemSelectList?.length">
        <div class="flex items-center justify-between">
          <div style="font-size: 14px">
            选择机构越多，<span style="color: #fcba72">获得额度机会更高</span>
          </div>

          <div class="flex items-center">
            <div class="q-mr-xs">全选</div>
            <div class="center" @click="selectAllHandler">
              <img v-if="!isSelectAll" src="~/assets/images/public/nu_select_op.png" style="width: 16px" />
              <img v-else src="~/assets/images/public/ok_select.png" style="width: 16px" />
            </div>
          </div>
        </div>

        <div class="progress-box" style="margin-top: 14px">
          <div class="progress-bg"></div>
          <div class="progress" :style="{ width: `${progressOneAPIB}%` }">
            <div class="mark"></div>
          </div>
        </div>

        <div v-for="(item, index) in orderItemSelectList" :key="index" class="list-item q-py-md"
          :class="{ 'q-mt-md': !index }">
          <div class="flex items-center">
            <div v-if="item?.companyLogo" class="center q-mr-xs">
              <img :src="item.companyLogo" style="width: 25px; border-radius: 99999px" />
            </div>
            <div class="text-weight-bold">{{ item.companyName || '' }}</div>
          </div>
          <div class="flex items-center justify-between">
            <div class="q-mr-sm">
              <div class="text-weight-bold" style="font-size: 16px; margin-top: 10px">
                {{ item.companyTitle || '' }}
              </div>
              <div style="color: #999; font-size: 13px" class="q-mt-xs">{{ item.companySubTitle || '' }}</div>
            </div>
            <div @click="orderItemClickHandler(item)" class="center">
              <img v-if="orderItemSelectOkList.includes(item)" src="~/assets/images/public/ok_select.png"
                style="width: 16px" />
              <img v-else src="~/assets/images/public/nu_select_op.png" style="width: 16px" />
            </div>
          </div>
          <div v-if="!!item.protocolUrl" class="q-mt-sm">
            <iframe :src="item.protocolUrl" style="border: 0; margin: 0; padding: 0; outline: none; height: 160px"
              class="full-width block"></iframe>
          </div>
        </div>
      </div>
    </section>

    <div style="height: 100px"></div>
    <div class="bottom-action-box q-pa-md">
      <q-btn label="立即申请" padding="none none" unelevated rounded @click="submit" class="full-width" style="
          background-color: #096AFF;
          color: #fff;
          padding: 8px 18px !important;
          font-size: 15px;
          font-weight: 600;
        " />
    </div>
    <Protocol ref="ProtocolRef" @again-half="againHalf" @next-half="nextHalf"/>
    <BackInfoDialog ref="BackInfoDialogRef" :prod-name="orderItemTop?.companyName" :prod-img="orderItemTop?.companyLogo"
      :is-customize-goto="true" :back-style="1" @goto="submit" />
    <!-- <TipsDialog ref="TipsDialogRef"  /> -->
  </q-page>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, toRaw, unref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Protocol from './dialog/Protocol.vue';
import { ProtocolInstance } from './dialog/Protocol';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { computed } from 'vue';
import { MatchResultOrderItemList } from 'src/types/matchResult';
import { baseApiUrl } from 'src/config/env.config';
import BackInfoDialog from 'src/components/BackInfoDialog.vue';
import { BackInfoDialogInstance } from 'src/components/BackInfoDialog';
import { APIBItem } from 'src/types/apib';
const isHalf = ref(false);
const router = useRouter();
const ProtocolRef = ref<ProtocolInstance>();
const BackInfoDialogRef = ref<BackInfoDialogInstance>();
const route = useRoute()
const count = ref(0)
const matchData = computed(() => {
  return useMechanismStore().matchData;
});
const halfMatchData = computed(() => {
  return useMechanismStore().halfMatchData;
})
const orderItemTop = computed(() => {
  if (isHalf.value) {
    return {
      ...halfMatchData.value?.[0],
      infoType: ''
    };
  }
  if (matchData.value) {
    const { orderItemList } = matchData.value;
    if (orderItemList.length < 1) return;
    return orderItemList[0];
  };
});

const orderItemSelectList = computed(() => {
  if (!matchData.value) return;
  const { orderItemList } = matchData.value;
  if (orderItemList.length < 2) return;
  return orderItemList.slice(1, orderItemList.length);
});
watch(matchData, () => {
  if (!matchData.value?.orderItemList && !halfMatchData.value?.[0] && route.path == '/mechanism') {
    console.log(!matchData.value?.orderItemList && !halfMatchData.value?.[0], route.path == '/mechanism')
    router.replace('/waitpage')
    return
  }
}, {
  deep: true,
  immediate: true
})
// 当前选择申请list
const orderItemSelectOkList = ref<MatchResultOrderItemList[]>([]);

// 当前选择申请list + 必申请item
const okItemList = computed(() => {
  if (matchData.value?.orderItemList?.length && orderItemTop.value) {
    return [orderItemTop.value, ...orderItemSelectOkList.value];
  }
  return [];
});

watch(orderItemSelectList, (val) => {
  orderItemSelectOkList.value = val ? orderItemSelectOkList.value.filter((item) => val.includes(item)) : [];
});

const orderItemClickHandler = (item: MatchResultOrderItemList) => {
  if (orderItemSelectOkList.value.includes(item)) {
    orderItemSelectOkList.value = orderItemSelectOkList.value.filter((itemData) => itemData !== item);
  } else {
    orderItemSelectOkList.value.push(item);
  }
};

const progress = computed(() => {
  if (!orderItemSelectList.value?.length) return 0;
  const count = orderItemSelectList.value.length;
  const num = orderItemSelectOkList.value.length;
  return +((num / count) * 100).toFixed(0);
});

const selectAllList = computed(() => {
  if (!orderItemSelectList.value?.length) return [];
  const oneIndex = orderItemSelectList.value.findIndex((item) => item.infoType === 'APIB');
  return orderItemSelectList.value.filter((item, index) => item.infoType !== 'APIB' || index === oneIndex);
});

const progressOneAPIB = computed(() => {
  if (!orderItemSelectList.value?.length) return 0;
  const count = selectAllList.value.length;
  const num = orderItemSelectOkList.value.length;
  if (count === 0) return 0;
  return +((num / count) * 100).toFixed(0);
});

const isSelectAll = computed(() => {
  if (!orderItemSelectList.value?.length) return false;
  const count = selectAllList.value.length;
  const num = orderItemSelectOkList.value.length;
  if (count === 0) return false;
  return count <= num;
});

const selectAllHandler = () => {
  if (!orderItemSelectList.value) return;
  orderItemSelectOkList.value = !isSelectAll.value ? [...selectAllList.value] : [];
};
const routerBack = () => {
  if (count.value == 0) {
    submit()
  } else {
    BackInfoDialogRef.value?.show();
  }
}
const submit = () => {
  if (!ProtocolRef.value) return;
  if (ProtocolRef.value.isShow()) return;
  const param =
    okItemList.value.length && matchData.value
      ? {
        orderId: matchData.value.orderId,
        itemOrderIds: JSON.stringify(okItemList.value.map((item) => item.orderItemId)),
        approveUrl: okItemList.value.find((item) => item.infoType === 'APIB')?.approveUrl,
      }
      : undefined;
  const getAgreement = () => {
    if (okItemList.value.length && matchData.value) {
      const urlTemp = matchData.value.orderProtocolUrl ?? '';
      console.log(okItemList.value.map((item) => item.orderItemId));
      const ids = okItemList.value.map((item) => item.orderItemId).join('-');
      console.log(ids);
      return `${baseApiUrl}${urlTemp.replace('{}', ids)}`;
    }
    return;
  };
  if (isHalf.value) {
    ProtocolRef.value.show(halfMatchData.value?.[0]?.htmlContent, {
      orderId: halfMatchData.value?.[0]?.orderId || '',
      itemOrderIds: JSON.stringify([halfMatchData.value?.[0]?.orderItemId]),
      approveUrl: halfMatchData.value?.[0]?.approveUrl,
      apibItem: halfMatchData.value?.[0]
    });
  } else {
    ProtocolRef.value.show(getAgreement(), param);
  }
  count.value++
};

const popstateHandler = (e: PopStateEvent) => {
  routerBack()
  setTimeout(() => {
    window.history.pushState({ mechanismPage: true }, 'mechanismPage', window.location.href);
  });
};
const againHalf = (res: APIBItem[]) => {
  useMechanismStore().setHalfMatchData(res);
  isHalf.value = true;
  useMechanismStore().resetMatchData();
}
const nextHalf = () => {
  if(halfMatchData.value?.length && halfMatchData.value?.length > 0){
    useMechanismStore().setHalfMatchData(halfMatchData.value.slice(1));
  }
}
onMounted(() => {
  isHalf.value = route.query.isHalf === '1' ? true : false
  if(!matchData.value){
    isHalf.value = true
  }
  console.log(123)
  window.history.pushState({ mechanismPage: true }, 'mechanismPage', window.location.href);
  window.addEventListener('popstate', popstateHandler);
  // getApiBOrderList();
  nextTick(() => {
    selectAllHandler()
  })
});

onUnmounted(() => {
  window.removeEventListener('popstate', popstateHandler);
});
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff;
}

.bottom-action-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid rgba($color: #ccc, $alpha: 0.4);
  box-shadow: rgba(99, 99, 99, 0.2) 0px 0px 1px 0px;
}

.mechanism-card {
  background: #ffffff;
  box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.07);
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  background-image: url(src/assets/images/mechanism/card.png);
  background-repeat: no-repeat;
  background-size: 100% auto;

  .mark {
    position: absolute;
    right: 0;
    top: 0;

    .mark-text {
      background: #096AFF;
      color: #fff;
      border-radius: 0px 0px 0px 8px;
      font-size: 12px;
      font-weight: bold;
      padding: 2px 10px;
    }
  }
}

.select-card {
  background-color: #ffffff;
  box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.07);
  border-radius: 8px;
  background-image: url(src/assets/images/mechanism/card.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  overflow: hidden;
}

.progress-box {
  $height: 14px;
  height: $height;
  position: relative;
  border-radius: 99999px;
  overflow: hidden;

  .progress-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 99999px;
    background-color: #ffeee5;
  }

  .progress {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    transition-duration: 300ms;
    border-radius: 99999px;
    background-color: #096AFF;

    .mark {
      position: absolute;
      width: $height;
      height: $height;
      right: 0;
      top: 0;
      background: url(src/assets/images/mechanism/icon1.png) no-repeat;
      background-size: 100% 100%;
    }
  }
}

.list-item {
  border-bottom: 1px solid rgba($color: #d8d8d8, $alpha: 0.5);

  &:nth-last-child(1) {
    border-bottom: none;
  }
}
</style>
